// ShopCart 模块仓库 vuex~
import {reqCartList} from "@/api/index.js";
import {reqDeleteCartById} from "@/api/index.js";
import {reqUpdateCheckedById} from "@/api/index.js";
const actions = {
  async reqList({commit}) {
    let xml = await reqCartList();
    
    
    if(xml.status === 200) {
      commit("REQLIST", xml.data);
    }    
  },

  async deleteCartById({commit}, skuId) {
    let xml = await reqDeleteCartById(skuId);

    if(xml.data.code === 200) {
      return "ok"
    }else {
      return Promise.reject(new Error("FALSE"));
    }    
  },

  async reqUpdateCheckedById({commit}, {skuId, isCheckef}) {
    let xml = await reqUpdateCheckedById(skuId, isCheckef);
    if(xml.data.code === 200) {  
      return "ok"
    }else {
      return Promise.reject(new Error("FALSE"));
    }    
  },

  async deleteAllCheckedCart({dispatch, getters}) {
    let pr = [];
    getters.cartList.cartInfoList.forEach((e) => {
      if(e.isChecked === 1) {
        let prs = dispatch("deleteCartById", e.skuId);
        
        pr.push(prs);
      }      
    })    

    return Promise.all(pr);    
  }
};

const mutations = {    
  REQLIST(state, value) {
    state.cartList = value;
  }
};

const state = {  
  cartList: null,
};

const getters = {
  cartList(state) {   
    return state.cartList ? state.cartList.data[0] : false;
  }
};

export default {
  actions,
  mutations,
  state,
  getters,
}
 